package club.hicode.daydayup.protostuff;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.jsonzou.jmockdata.JMockData;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Protobuf 的单元测试
 *
 * @author Liu Chunfu
 * @date 2018-05-02 下午3:22
 **/
public class TestProtobuf {

    @Test
    public void test1() {

        Address address = new Address("address");
        Student student = new Student("lcf", "00018", CollectionUtil.newArrayList("s1", "s2")
                , 18, address);
        System.out.println(student);
        byte[] serializer = ProtostuffUtil.serializer(student);
        System.out.println(Arrays.toString(serializer));

        Student deserializer = ProtostuffUtil.deserializer(serializer, Student.class);
        System.out.println(deserializer);

    }

    @Test
    public void speedTest() {

        int size = 10000;
        List<Student> studentList = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            Student mock = JMockData.mock(Student.class);
            studentList.add(mock);
        }

        //热身
        studentList.forEach(s -> {
            String s1 = JSON.toJSONString(s);
            JSON.parseObject(s1, new TypeReference<Student>() {
            });
        });
        studentList.forEach(s -> {
            byte[] s1 = ProtostuffUtil.serializer(s);
            ProtostuffUtil.deserializer(s1, Student.class);
        });

        //
        long t1 = System.currentTimeMillis();
        studentList.forEach(s -> {
            byte[] s1 = ProtostuffUtil.serializer(s);
            ProtostuffUtil.deserializer(s1, Student.class);
        });
        long t2 = System.currentTimeMillis();

        studentList.forEach(s -> {
            String s1 = JSON.toJSONString(s);
            JSON.parseObject(s1, new TypeReference<Student>() {
            });
        });
        long t3 = System.currentTimeMillis();

        System.out.println("fastJson:" + (t2 - t1));
        System.out.println("protobuf:" + (t3 - t2));
    }
}
